package com.qf.myrbac.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //注意，这里对bean的name有要求：shiroFilterFactoryBean
    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        Map<String, String> map = new LinkedHashMap<>();
        //放行的请求
        map.put("/register.html", "anon");
        map.put("/login.html", "anon");
        map.put("/swagger-ui.html", "anon");
        map.put("/doc.html", "anon");
        map.put("/webjars/**", "anon");
        map.put("/swagger-resources/**", "anon");
        map.put("/v2/**", "anon");
        map.put("/statics/**", "anon");
        map.put("/captcha.jpg", "anon");
        map.put("/sys/login", "anon");
        //需要登陆才能请求的URL
        map.put("/**", "authc");
        chainDefinition.addPathDefinitions(map);
        return chainDefinition;
    }

    @Bean
    public Realm customRealm() {
        CustomRealm customRealm = new CustomRealm();
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName(ShiroConstants.HASH_ALGORIHMNAME);
        credentialsMatcher.setHashIterations(ShiroConstants.HASH_ITERATIONS);
        customRealm.setCredentialsMatcher(credentialsMatcher);
        // 整合缓存配置
        customRealm.setCacheManager(new EhCacheManager());
        // 开启缓存
        customRealm.setCachingEnabled(true);
        // 开启身份认证缓存
        customRealm.setAuthenticationCachingEnabled(true);
        // 开启授权数据缓存
        customRealm.setAuthorizationCachingEnabled(true);

        return customRealm;
    }
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();
        creator.setProxyTargetClass(true);
        return creator;
    }
}
